using Microsoft.AspNetCore.Mvc;
using GenericRepositoryDemo.Domain.Orders;
using Microsoft.EntityFrameworkCore;
using GenericRepositoryDemo.Domain.Abstracts.Repositories;

namespace GenericRepositoryDemo.Api.Controllers;

[ApiController]
[Route("[controller]")]
public class OrderController : ControllerBase
{
    private readonly IRepository<Order, int> _orderRepository;
    private readonly IOrderCustomRepository _orderCustomRepository;

    public OrderController(IRepository<Order, int> orderRepository, IOrderCustomRepository orderCustomRepository)
    {
        _orderRepository = orderRepository;
        _orderCustomRepository = orderCustomRepository;
    }

    [HttpGet("{id}")]
    public async Task<Order> GetAsync(int id)
    {
        var orderQueryable = await _orderRepository.WithDetailsAsync(o => o.OrderItems);
        return await orderQueryable.FirstAsync(o => o.Id == id);
    }

    [HttpGet]
    public async Task<List<Order>> GetListAsync()
    {
        var orderQueryable = await _orderRepository.WithDetailsAsync(o => o.OrderItems);
        return await orderQueryable.ToListAsync();
    }

    [HttpPost]
    public async Task<int> CreateAsync(string name)
    {
        var order = new Order()
        {
            Name = name,
            CreateDate = DateTime.UtcNow,
            OrderItems = new List<OrderItem>()
            {
                new OrderItem()
                {
                    ProductId = 1,
                    Amount = 1,
                }
            }
        };
        order = await _orderRepository.InsertAsync(order, autoSave: true);

        return order.Id;
    }

    [HttpPut("{id}")]
    public async Task<int> UpdateAsync(int id, string name)
    {
        var orderQueryable = await _orderRepository.WithDetailsAsync(o => o.OrderItems);
        var order = await orderQueryable.FirstAsync(o => o.Id == id);
        order.Name = name;
        order = await _orderRepository.UpdateAsync(order, autoSave: true);
        return order.Id;
    }

    [HttpDelete("{id}")]
    public async Task DeleteAsync(int id)
    {
        await _orderRepository.DeleteAsync(id, autoSave: true);
    }
}